package com.bawei.module_mine.ui

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.library_common.route.ARouterActivityPath
import com.bawei.library_common.utils.DataStoreUtils
import com.bawei.library_common.utils.GsonUtil
import com.bawei.library_mvi.ui.BaseMviActivity
import com.bawei.module_mine.R
import com.bawei.module_mine.databinding.MineActivityLoginBinding
import com.bawei.module_mine.intent.LoginIntent
import com.bawei.module_mine.state.LoginState
import com.bawei.module_mine.viewmodel.LoginViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = ARouterActivityPath.PAGER_LOGIN)
class LoginActivity : BaseMviActivity<MineActivityLoginBinding>() {
    private lateinit var loginViewModel:LoginViewModel
    //处理
    override fun handleState() {
        //
        lifecycleScope.launch {
            loginViewModel.states.collect{
                when(it){
                    is LoginState.loginFailed -> it.message?.let { it1 -> showMsg(it1) }
                    is LoginState.loginSuccess -> {
                       showMsg("登陆成功")
                        //将token和UserEntity 存储到dataStore
                        DataStoreUtils.putData("token",it.result.token)
                        //将UserEntity对象-》json字符串（把null过滤掉）
                        DataStoreUtils.putData("user",GsonUtil.toJsonFilterNullField(it.result))
                        finish()

                    }
                    is LoginState.loginInit -> {}
                }
            }
        }
    }

    override fun getLayout(): Int {
        return R.layout.mine_activity_login
    }

    override fun initEvent() {
        super.initEvent()
        viewDataBinding.btLogin.setOnClickListener {
            val usernameStr = viewDataBinding.etUsername.text.trim().toString()
            val passwordStr = viewDataBinding.etPassword.text.trim().toString()
            if(TextUtils.isEmpty(usernameStr)){
                showMsg("用户名不能为空")
                return@setOnClickListener
            }
            if(TextUtils.isEmpty(passwordStr)){
                showMsg("密码不能为空")
                return@setOnClickListener
            }
            lifecycleScope.launch {
                loginViewModel.intents.send(LoginIntent.Login(usernameStr,passwordStr))
            }

        }
    }

    override fun generateViewModel() {
        loginViewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
    }

}